package com.example.mqtt.utils;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttReceiverUtil {
    private static final int QoS = 1;
    private static final String Host = "tcp://127.0.0.1:1883";
    private static MqttClient mqttClient = null;

    public static void init(String clientId) throws MqttException {
        assert null != clientId : "client id is null";
        // 初始化MqttClient
        mqttClient = new MqttClient(Host, clientId, new MemoryPersistence());
        // 初始化连接设置对象
        MqttConnectOptions options = new MqttConnectOptions();
        // 客户端断开连接时清除所有状态
        options.setCleanSession(true);
        // 设置连接超时
        options.setConnectionTimeout(30);
        // 设置心跳间隔时间
        options.setKeepAliveInterval(45);
        // 设置用户名
        options.setUserName("admin");
        // 设置密码
        options.setPassword("123456".toCharArray());
        if (!mqttClient.isConnected()) {
            mqttClient.setCallback(new MyMqttCallback());
            mqttClient.connect(options);
        }
    }

    public static void receive(String topic) throws MqttException {
        if (null == mqttClient || !mqttClient.isConnected()) init("1");
        int[] Qos = {QoS};
        String[] topics = {topic};
        mqttClient.subscribe(topics, Qos);
    }
}
